<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Android 日志查看器</title>
  <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="node_modules/highlight.js/styles/github.css">
  <link rel="stylesheet" href="styles.css">
  <!-- React 依赖 -->
  <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>

</head>
<body>
  <div class="app-container">
    <!-- 左侧面板 -->
    <div class="left-panel">
      <!-- 文件拖拽区域 -->
      <div class="drop-zone">
        <div class="drop-area" id="dropArea">
          <p>将 logger 文件夹拖放到此处</p>
          <button id="browseBtn" class="btn">浏览文件/夹</button>
        </div>
      </div>
      
      <!-- 目录结构 -->
      <div class="directory-panel">
        <div id="directoryStructure" class="d-none">
          <h5>文件结构</h5>
          <div id="treeView" class="tree-view"></div>
        </div>
      </div>
    </div>
    
    <!-- 分隔条 -->
    <div class="resizer" id="resizer"></div>
    
    <!-- 右侧内容区域 -->
    <div class="right-panel">
      <!-- 内容头部 -->
      <div class="content-header">
        <h4 id="contentTitle">概述</h4>
        <div class="header-actions">
          <!-- 日志分析按钮 (仅在查看描述时显示) -->
          <button id="logAnalysisBtn" class="btn btn-outline-primary d-none" onclick="handleLogAnalysisClick()">
            📊 日志分析
          </button>
          <!-- 搜索栏容器 (仅在查看logger文件时显示) -->
          <div id="headerSearchContainer" class="d-none"></div>
        </div>
      </div>
      
      <!-- 内容主体 -->
      <div class="content-body">
        <!-- 默认概述页面 -->
        <div id="overviewContent" class="overview-content">
          <div class="overview-section">
            <h5>📋 项目概述</h5>
            <div class="card">
              <div class="card-body">
                <p class="text-muted">请拖拽或选择 logger 文件夹以开始查看日志内容。</p>
                <p>支持的功能：</p>
                <ul>
                  <li>📁 自动解析文件结构</li>
                  <li>📝 查看环境信息和问题描述</li>
                  <li>🔍 高性能日志查看和搜索</li>
                  <li>🖼️ 截图预览</li>
                  <li>🎨 语法高亮显示</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 环境信息 -->
        <div id="environmentInfo" class="d-none">
          <div id="envDetails" class="card">
            <div class="card-body">
              <div id="envContent"></div>
            </div>
          </div>
        </div>
        
        <!-- 问题描述 -->
        <div id="problemDescription" class="d-none">
          <div id="descriptionDetails" class="card">
            <div class="card-body">
              <div id="descriptionContent"></div>
            </div>
          </div>
        </div>
        
        <!-- 日志内容 -->
        <div id="logContent" class="d-none">
          <div class="card">
            <div class="card-body p-0">
              <!-- React LogViewer Container -->
              <div id="react-log-container" style="height: 100%; overflow: auto;"></div>
            </div>
          </div>
        </div>
        
        <!-- 图片查看器 -->
        <div id="imageViewer" class="d-none">
          <div class="card">
            <div class="card-body text-center">
              <img id="imageContent" class="img-fluid" src="" alt="截图">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- React 组件内联实现 -->
  <script>
    // 创建 LogViewer 组件
    const { useState, useEffect, useRef } = React;
    
    // LogViewer 组件
    function LogViewer({ content, searchTerm, onSearchTermChange }) {
      const [filteredLines, setFilteredLines] = useState([]);
      const [currentSearchIndex, setCurrentSearchIndex] = useState(-1);
      const [searchMatches, setSearchMatches] = useState([]);
      const containerRef = useRef(null);
      
      useEffect(() => {
        if (!content) {
          setFilteredLines([]);
          return;
        }
        
        const lines = content.split('\n');
        setFilteredLines(lines);
      }, [content]);
      
      useEffect(() => {
        if (!searchTerm || !filteredLines.length) {
          setSearchMatches([]);
          setCurrentSearchIndex(-1);
          return;
        }
        
        const matches = [];
        filteredLines.forEach((line, index) => {
          if (line.toLowerCase().includes(searchTerm.toLowerCase())) {
            matches.push(index);
          }
        });
        
        setSearchMatches(matches);
        setCurrentSearchIndex(matches.length > 0 ? 0 : -1);
        
        // 滚动到第一个匹配项
        if (matches.length > 0) {
          scrollToLine(matches[0]);
        }
      }, [searchTerm, filteredLines]);
      
      const scrollToLine = (lineIndex) => {
        if (containerRef.current) {
          const lineElement = containerRef.current.querySelector(`[data-line="${lineIndex}"]`);
          if (lineElement) {
            lineElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        }
      };
      
      const highlightText = (text, searchTerm) => {
        if (!searchTerm) return text;
        
        const regex = new RegExp(`(${searchTerm})`, 'gi');
        return text.replace(regex, '<mark>$1</mark>');
      };
      
      const getLineClass = (line) => {
        if (line.includes('FATAL') || line.includes('AndroidRuntime')) {
          return 'log-line-error';
        }
        if (line.includes('ERROR') || line.includes('E/')) {
          return 'log-line-error';
        }
        if (line.includes('WARN') || line.includes('W/')) {
          return 'log-line-warning';
        }
        if (line.includes('INFO') || line.includes('I/')) {
          return 'log-line-info';
        }
        if (line.includes('DEBUG') || line.includes('D/')) {
          return 'log-line-debug';
        }
        return 'log-line-default';
      };
      
      return React.createElement('div', {
        ref: containerRef,
        className: 'log-viewer-container',
        style: {
          fontFamily: 'Monaco, Consolas, "Courier New", monospace',
          fontSize: '12px',
          lineHeight: '1.4',
          backgroundColor: '#f8f9fa',
          border: '1px solid #dee2e6',
          borderRadius: '4px',
          height: '100%',
          overflowX: 'auto',
          overflowY: 'auto',
          padding: '8px'
        }
      }, filteredLines.map((line, index) => {
        const isMatch = searchMatches.includes(index);
        const isCurrentMatch = currentSearchIndex >= 0 && searchMatches[currentSearchIndex] === index;
        
        return React.createElement('div', {
          key: index,
          'data-line': index,
          className: `log-line ${getLineClass(line)} ${isMatch ? 'search-match' : ''} ${isCurrentMatch ? 'current-match' : ''}`,
          style: {
            padding: '2px 4px',
            borderLeft: isCurrentMatch ? '3px solid #007bff' : 'none',
            backgroundColor: isCurrentMatch ? '#e3f2fd' : (isMatch ? '#fff3cd' : 'transparent'),
            whiteSpace: 'nowrap',
            overflow: 'visible',
            minWidth: 'max-content'
          },
          dangerouslySetInnerHTML: {
            __html: `<span style="color: #6c757d; margin-right: 8px;">${(index + 1).toString().padStart(4, ' ')}</span>${highlightText(line, searchTerm)}`
          }
        });
      }));
    }
    
    // SearchBar 组件
    function SearchBar({ searchTerm, onSearchTermChange, placeholder = "搜索日志内容..." }) {
      return React.createElement('div', {
        className: 'search-bar-container',
        style: {
          padding: '8px',
        }
      }, [
        React.createElement('input', {
          key: 'search-input',
          type: 'text',
          className: 'form-control',
          placeholder: placeholder,
          value: searchTerm,
          onChange: (e) => onSearchTermChange(e.target.value),
          style: {
            fontSize: '14px'
          }
        })
      ]);
    }
    
    // 全局搜索状态管理
    let globalSearchTerm = '';
    let globalSearchSetter = null;
    let headerSearchRoot = null;
    
    // 渲染函数
    function renderLogViewer(options) {
      // 支持两种调用方式：新的 options 对象和旧的 (containerId, content) 参数
      let containerId, content, isLoggerFile = false;
      
      if (typeof options === 'string') {
        // 旧的调用方式：renderLogViewer(containerId, content)
        containerId = options;
        content = arguments[1];
      } else if (options && typeof options === 'object') {
        // 新的调用方式：renderLogViewer({content, logType, fileName})
        containerId = 'react-log-container'; // 默认容器ID
        content = options.content;
        isLoggerFile = options.logType === 'logger';
        console.log('渲染日志内容:', {
          logType: options.logType,
          fileName: options.fileName,
          contentLength: content ? content.length : 0,
          isLoggerFile: isLoggerFile
        });
      } else {
        console.error('Invalid parameters for renderLogViewer:', options);
        return;
      }
      
      const container = document.getElementById(containerId);
      if (!container) {
        console.error('Container not found:', {containerId, options});
        return;
      }
      
      // 如果是logger文件，将搜索栏渲染到header区域
      if (isLoggerFile) {
        const headerSearchContainer = document.getElementById('headerSearchContainer');
        if (headerSearchContainer) {
          headerSearchContainer.classList.remove('d-none');
          
          function HeaderSearchBar() {
            const [searchTerm, setSearchTerm] = useState(globalSearchTerm);
            
            useEffect(() => {
              globalSearchSetter = setSearchTerm;
              return () => {
                globalSearchSetter = null;
              };
            }, []);
            
            const handleSearchChange = (value) => {
              setSearchTerm(value);
              globalSearchTerm = value;
              // 触发LogViewer重新渲染
              if (window.currentLogViewerSetter) {
                window.currentLogViewerSetter(value);
              }
            };
            
            return React.createElement(SearchBar, {
              searchTerm: searchTerm,
              onSearchTermChange: handleSearchChange,
              placeholder: "搜索日志内容..."
            });
          }
          
          if (!headerSearchRoot) {
            headerSearchRoot = ReactDOM.createRoot(headerSearchContainer);
          }
          headerSearchRoot.render(React.createElement(HeaderSearchBar));
        }
      } else {
        // 隐藏header搜索栏
        const headerSearchContainer = document.getElementById('headerSearchContainer');
        if (headerSearchContainer) {
          headerSearchContainer.classList.add('d-none');
        }
      }
      
      function LogViewerApp() {
        const [searchTerm, setSearchTerm] = useState(globalSearchTerm);
        
        useEffect(() => {
          window.currentLogViewerSetter = setSearchTerm;
          return () => {
            window.currentLogViewerSetter = null;
          };
        }, []);
        
        return React.createElement('div', {
          className: 'log-viewer-app',
          style: { height: '100%' }
        }, [
          React.createElement(LogViewer, {
            key: 'log-viewer',
            content: content,
            searchTerm: searchTerm,
            onSearchTermChange: setSearchTerm
          })
        ]);
      }
      
      const root = ReactDOM.createRoot(container);
      root.render(React.createElement(LogViewerApp));
    }
    
    // 创建全局 LogViewerComponents 对象
    window.LogViewerComponents = {
      LogViewer: LogViewer,
      SearchBar: SearchBar,
      renderLogViewer: renderLogViewer
    };
    
    console.log('LogViewerComponents已正确初始化:', window.LogViewerComponents);
  </script>
  <script src="renderer.js"></script>
</body>
</html>